<template>
  <a-dropdown trigger="click">
    <span>
      <a-avatar shape="square" :src="avatar" :alt="username" />
      <span class="username">{{ username }}</span>
    </span>
    <template #overlay>
      <a-menu @click="handleMenuClick">
        <a-menu-item key="userinfo">
          <span class="navname">
            <UserOutlined />
            <span style="margin-left: 2px">用户信息</span>
          </span>
        </a-menu-item>
        <a-menu-item key="logout">
          <span class="navname">
            <LogoutOutlined />
            <span style="margin-left: 2px">退出登录</span>
          </span>
        </a-menu-item>
      </a-menu>
    </template>
  </a-dropdown>
</template>

<script setup>
import { UserOutlined, LogoutOutlined } from "@ant-design/icons-vue";
import { ref, onMounted } from "vue";
import { useStore } from "vuex";
import router from "@/router/index";

// 假设这是从后端获取的用户信息
import avatar from "@/assets/images/pmys.gif"; // "https://example.com/path/to/avatar.jpg";

const store = useStore();
const username = ref("Admin");

const logout = () => {
  localStorage.removeItem("localUser");
  store.commit("logout");
};

const handleMenuClick = ({ key }) => {
  if (key === "userinfo") {
    console.log("用户信息");
  } else if (key === "logout") {
    console.log("退出登录");
    logout();
    router.push({ name: "login" });
  }
};

onMounted(() => {
  const lu = localStorage.getItem("localUser");
  // 检查是否有本地存储
  if (lu) {
    // 载入本地存储的用户名
    const localUser = JSON.parse(lu);
    username.value = localUser.username;
  }
});
</script>

<style scoped>
.username {
  margin-left: 10px;
  line-height: 60px;
  font-size: 17px;
  color: #ffffff;
  font-weight: bold;
}

.navname {
  display: flex;
  justify-content: left;
  align-items: center;
}

/* 下拉菜单样式 */
.ant-dropdown-trigger {
  cursor: pointer;
}

.ant-dropdown-menu {
  min-width: 100px;
}

/* 调整下拉菜单的位置 */
.ant-dropdown-menu {
  min-width: 100px;
  margin-top: 30px; /* 添加额外的顶部边距 */
}

.ant-dropdown-menu-item {
  padding: 8px 16px;
}

.ant-dropdown-menu-item:hover {
  background-color: #f5f5f5;
}
</style>
